
#region copyright notice
/* ====================================================================
 * The UncleGED Open Source Software License
 *
 * Copyright (c) 1999-2009 D. M. DeBacker. All rights reserved.
 * http://gatheringleaves.org/uged
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. Products derived from this software may not be called "UncleGED",
 *    nor may "UncleGED" appear in their name, without prior written
 *    permission of D. M. DeBacker.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL D. M. DEBACKER BE LIABLE FOR ANY 
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 */
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

using UncleGED.Utils;
using UncleGED.Application;

//TODO: add tooltips to all options
namespace UGed
{
   public partial class OptionsDialog : Form
   {
      // These are the Win32 error code for file not found or access denied.
      const int ERROR_FILE_NOT_FOUND = 2;
      const int ERROR_ACCESS_DENIED = 5;

      UGedProject m_UGProj = new UGedProject();
      public UGedProject Project
      {
         get { return m_UGProj; }
      }

      string m_ProjectFileName = "";
      public string ProjectFileName
      {
         get { return m_ProjectFileName; }
      }

      bool m_DidSave = false;
      public bool DidSave
      {
         get { return m_DidSave; }
      }

      public OptionsDialog()
      {
         InitializeComponent();
      }

      public OptionsDialog(UGedProject ugp, string projectFileName)
      {
         InitializeComponent();
         m_UGProj = ugp;
         m_ProjectFileName = projectFileName;
         this.Text = "Uncle GED Project Settings";
      }

      private void options_Load(object sender, EventArgs e)
      {
         DisplaySettings();
      }


      private void DisplaySettings()
      {
         this.txtProjectName.Text = m_UGProj.ProjectName;
         //this.txtGEDCOMFile.Text = m_UGProj.GedComFile;

         this.chkPrivate.Checked = m_UGProj.Privacy;
         this.chkBackground.Checked = m_UGProj.UseBackground;
         this.chkBanner.Checked = m_UGProj.UseBanner;

         //this.chkDoCompileHtml.Checked = m_UGProj.DoCompileHTML;

         this.txtBackgroundImage.Text = m_UGProj.BackgroundFile;
         this.txtBannerImage.Text = m_UGProj.BannerFile;

         this.chkExcludeNotes.Checked = m_UGProj.ExcludeNotes;
         this.chkSourceInNewWindow.Checked = m_UGProj.SourcesInNewWindow;

         this.chkAddKeywords.Checked = m_UGProj.AddKeywords;
         this.chkSurnameCount.Checked = m_UGProj.AddSurnameCount;
         this.chkCreateListReport.Checked = m_UGProj.CreateListReport;
         this.chkCreateStatsPage.Checked = m_UGProj.CreateStatsPage;
         this.chkDisplayRIN.Checked = m_UGProj.DisplayRIN;
         this.chkDisplayMRIN.Checked = m_UGProj.DisplayMRIN;

         this.chkAddCopyright.Checked = m_UGProj.AddUserCopyright;
         this.chkCreateGendexFile.Checked = m_UGProj.CreateGendexFile;

         //this.chkWarnNonAnsi.Checked = m_UGProj.WarnNonAnsi;

         this.txtAuthorName.Text = m_UGProj.AuthorsName;
         this.txtEmail.Text = m_UGProj.AuthorsEmail;
         this.txtAuthorsURL.Text = m_UGProj.AuthorsUrl;

         this.chkCreateChronoPage.Checked = m_UGProj.CreateChronoPage;
         this.nudChronoCutoff.Value = m_UGProj.ChronoCutOff;

         this.txtFamFilePrefix.Text = m_UGProj.FamFilePrefix;

         this.chkSurnamesAllCaps.Checked = m_UGProj.SurnamesAllCaps;
         this.chkChronoLinks.Checked = m_UGProj.ChronoLinks;

         this.chkMostRecentOnPage.Checked = m_UGProj.MostRecentOnPage;
         this.chkMostRecentOnIndex.Checked = m_UGProj.MostRecentOnIndex;
         this.chkHighlight.Checked = m_UGProj.HiLiteMostRecent;

         this.chkCreateLocationsPage.Checked = m_UGProj.CreateLocPage;
         this.chkLocReverseOrder.Checked = m_UGProj.LocReverseOrder;
         this.chkLocDisplayEvents.Checked = m_UGProj.LocDisplayEventDates;

         if(m_UGProj.LocEstimateMethod == 0) this._optLocEstimated_0.Checked = true;
         if(m_UGProj.LocEstimateMethod == 1) this._optLocEstimated_1.Checked = true;
         if(m_UGProj.LocEstimateMethod == 2) this._optLocEstimated_2.Checked = true;

         this.chkCreateOccupationsPage.Checked = m_UGProj.CreateOccupationsPage;
         this.chkIgnoreOccupations.Checked = m_UGProj.IgnoreOccupations;
         this.chkOccLocEqualsOccText.Checked = m_UGProj.OccLocEqualsOccText;

			//this.chkUseCSS.Checked = m_UGProj.UseCSS;
         this.txtMainPageTitle.Text = m_UGProj.MainPageTitle;
         this.txtFirstFamily.Text = m_UGProj.FirstFamily.ToString();

         this.chkDoCompileHtml.Checked = m_UGProj.DoCompileHtml;
         this.txtHtmlHelpCompiler.Text = m_UGProj.HtmlHelpCompiler;

         this.chkExcludeIndvidualsBornAfter.Checked = m_UGProj.ExcludeLivingIndividualsAfterBirthCutOff;

         if(m_UGProj.BirthCutOffYears > this.nudBirthCutOffYears.Maximum) 
            m_UGProj.BirthCutOffYears = (int)this.nudBirthCutOffYears.Maximum;

         if(m_UGProj.BirthCutOffYears < this.nudBirthCutOffYears.Minimum)
            m_UGProj.BirthCutOffYears = (int)this.nudBirthCutOffYears.Minimum;

         this.nudBirthCutOffYears.Value = m_UGProj.BirthCutOffYears;

         this.chkDoDateEstimation.Checked = m_UGProj.DoDateEstimation;
         this.nudMaxLivingAge.Value = m_UGProj.MaxLivingAge;
         this.nudMinMarrAge.Value = m_UGProj.MinMarrAge;
         this.nudMinChildBirth.Value = m_UGProj.MinChildBirth;
         this.nudMaxChildBirth.Value = m_UGProj.MaxChildBirth;
         this.nudAbtEquals.Value = m_UGProj.AboutEquals;
         this.nudMaxAgeDif.Value = m_UGProj.MaxAgeDifference;
         this.nudMaxIterations.Value = m_UGProj.MaxIterations;
      }

      /// <summary>
      /// Get the settings from the dialog box and update the configuration
      /// </summary>
      private void GetSettings()
      {
         m_UGProj.ProjectName = this.txtProjectName.Text.Trim();
         //m_UGProj.GedComFile = this.txtGEDCOMFile.Text.Trim();

         m_UGProj.AuthorsName = this.txtAuthorName.Text.Trim();
         m_UGProj.AuthorsEmail = this.txtEmail.Text.Trim();
         m_UGProj.AuthorsUrl = this.txtAuthorsURL.Text.Trim();
         m_UGProj.MainPageTitle = this.txtMainPageTitle.Text.Trim();
         m_UGProj.ChronoCutOff = (short)this.nudChronoCutoff.Value;
         m_UGProj.FamFilePrefix = this.txtFamFilePrefix.Text.ToLower();

         if (m_UGProj.FamFilePrefix.Length < 3)
            m_UGProj.FamFilePrefix = m_UGProj.FamFilePrefix + new string('_', 3 - m_UGProj.FamFilePrefix.Length);

         if (_optLocEstimated_0.Checked == true) m_UGProj.LocEstimateMethod = 0;
         if (_optLocEstimated_1.Checked == true) m_UGProj.LocEstimateMethod = 1;
         if (_optLocEstimated_2.Checked == true) m_UGProj.LocEstimateMethod = 2;

         m_UGProj.BackgroundFile = this.txtBackgroundImage.Text;
         m_UGProj.BannerFile = this.txtBannerImage.Text;

         m_UGProj.CreateLocPage = this.chkCreateLocationsPage.Checked;
         m_UGProj.CreateOccupationsPage = this.chkCreateOccupationsPage.Checked;
         //m_UGProj.DisplayOptionBeforeBuild = this.chkDisplayOptionBeforeBuild.Check;
         m_UGProj.HiLiteMostRecent = this.chkHighlight.Checked;
         m_UGProj.IgnoreOccupations = this.chkIgnoreOccupations.Checked;
         m_UGProj.LocDisplayEventDates = this.chkLocDisplayEvents.Checked;
         m_UGProj.SourcesInNewWindow = this.chkSourceInNewWindow.Checked;
         m_UGProj.LocReverseOrder = this.chkLocReverseOrder.Checked;
         m_UGProj.MostRecentOnIndex = this.chkMostRecentOnIndex.Checked;
         m_UGProj.MostRecentOnPage = this.chkMostRecentOnPage.Checked;
         m_UGProj.OccLocEqualsOccText = this.chkOccLocEqualsOccText.Checked;
         m_UGProj.AddUserCopyright = this.chkAddCopyright.Checked;
         m_UGProj.AddKeywords = this.chkAddKeywords.Checked;
         m_UGProj.ChronoLinks = this.chkChronoLinks.Checked;
         m_UGProj.CreateChronoPage = this.chkCreateChronoPage.Checked;
         this.nudChronoCutoff.Visible = this.chkCreateChronoPage.Checked;
         this.lblChronoCutoff.Visible = this.chkCreateChronoPage.Checked;

         m_UGProj.CreateGendexFile = this.chkCreateGendexFile.Checked;

         m_UGProj.CreateListReport = this.chkCreateListReport.Checked;

         m_UGProj.CreateStatsPage = this.chkCreateStatsPage.Checked;
         m_UGProj.DisplayMRIN = this.chkDisplayMRIN.Checked;
         m_UGProj.DisplayRIN = this.chkDisplayRIN.Checked;

         m_UGProj.ExcludeNotes = this.chkExcludeNotes.Checked;
         m_UGProj.AddSurnameCount = this.chkSurnameCount.Checked;
         m_UGProj.SurnamesAllCaps = this.chkSurnamesAllCaps.Checked;
			//m_UGProj.UseCSS = this.chkUseCSS.Checked;
         //m_UGProj.WarnFileOverwrite = this.chkWarnFileOverwrite.Checked;
         //m_UGProj.WarnNonAnsi = this.chkWarnNonAnsi.Checked;
         m_UGProj.UseBackground = this.chkBackground.Checked;
         m_UGProj.UseBanner = this.chkBanner.Checked;
         m_UGProj.Privacy = this.chkPrivate.Checked;
         m_UGProj.FirstFamily = System.Int32.Parse(txtFirstFamily.Text);
         m_UGProj.DoCompileHtml = this.chkDoCompileHtml.Checked;
         m_UGProj.HtmlHelpCompiler = this.txtHtmlHelpCompiler.Text;

         m_UGProj.ExcludeLivingIndividualsAfterBirthCutOff = this.chkExcludeIndvidualsBornAfter.Checked;
         m_UGProj.BirthCutOffYears = (int)this.nudBirthCutOffYears.Value;

         m_UGProj.DoDateEstimation = this.chkDoDateEstimation.Checked;
         m_UGProj.MaxLivingAge = (int)this.nudMaxLivingAge.Value;
         m_UGProj.MinMarrAge = (int)this.nudMinMarrAge.Value;
         m_UGProj.MinChildBirth = (int)this.nudMinChildBirth.Value;
         m_UGProj.MaxChildBirth = (int)this.nudMaxChildBirth.Value;
         m_UGProj.AboutEquals = (int)this.nudAbtEquals.Value;
         m_UGProj.MaxAgeDifference = (int)this.nudMaxAgeDif.Value;
         m_UGProj.MaxIterations = (int)this.nudMaxIterations.Value;

      }

      private string LongDirFix(string sIncomming, int iMax)
      {
         int I;
         int LblLen;
         //			int StringLen;
         string TempString;
         StringFunctions sf = new StringFunctions();

         TempString = sIncomming;
         LblLen = iMax;
         if (sf.Len(TempString) <= LblLen)
         {
            return TempString;
         }
         LblLen = LblLen - 6;
         for (I = sf.Len(TempString) - LblLen; I <= sf.Len(TempString); I++)
         {
            if (sf.Mid(TempString, I, 1) == "\\") break;
         } //
         return sf.Left(TempString, 3) + "..." + sf.Right(TempString, sf.Len(TempString) - (I - 1));
      }

      private void saveToolStripMenuItem_Click(object sender, EventArgs e)
      {
         m_UGProj.ProjectName = this.txtProjectName.Text;

         GetSettings();
         ConfigReader.SaveProject(m_ProjectFileName, m_UGProj);
         m_DidSave = true;
      }

      private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
      {
         string path = FolderMethods.GetUserPath();

         // Set the properties on SaveFileDialog1 so the user is 
         // prompted to create the file if it doesn't exist 
         // or overwrite the file if it does exist.
         SaveFileDialog1.Title = "Save Project As...";
         SaveFileDialog1.CreatePrompt = true;
         SaveFileDialog1.OverwritePrompt = true;

         // Set the file name to myText.txt, set the type filter
         // to text files, and set the initial directory to drive C.
         SaveFileDialog1.FileName = Path.GetFileName(m_ProjectFileName);
         SaveFileDialog1.DefaultExt = Path.GetExtension(m_ProjectFileName);
         SaveFileDialog1.Filter = "Uncle GED Project Files (*.ugproj)|*.ugproj";
         SaveFileDialog1.InitialDirectory = path;

         // Call ShowDialog and check for a return value of DialogResult.OK,
         // which indicates that the file was saved. 
         DialogResult result = SaveFileDialog1.ShowDialog();
         

         if (result == DialogResult.OK)
         {
            GetSettings();
            m_ProjectFileName = SaveFileDialog1.FileName;

            ConfigReader.SaveProject(m_ProjectFileName, m_UGProj);

            m_DidSave = true;
         }

      }

      private void closeToolStripMenuItem_Click(object sender, EventArgs e)
      {
         m_UGProj.ProjectName = this.txtProjectName.Text;

         GetSettings();
         ConfigReader.SaveProject(m_ProjectFileName, m_UGProj);
         m_DidSave = true;

         this.Hide();
      }

      private void openMenuItem_Click(object sender, EventArgs e)
      {
         string path = FolderMethods.GetUserPath();

         openFileDialog1.FileName = Path.GetFileName(m_ProjectFileName);
         openFileDialog1.InitialDirectory = path;
         openFileDialog1.Filter = "Uncle GED Project Files (*.ugproj)|*.ugproj";
         openFileDialog1.FilterIndex = 1;
         openFileDialog1.RestoreDirectory = false;

         if (openFileDialog1.ShowDialog() == DialogResult.OK)
         {
            m_ProjectFileName = openFileDialog1.FileName;
            m_UGProj = ConfigReader.LoadProject(m_ProjectFileName);
            this.txtProjectName.Text = m_UGProj.ProjectName;
            DisplaySettings();
         }

         m_DidSave = true;
      }

      private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
      {
         Process myProcess = new Process();
         string path = FolderMethods.GetAppPath();

         try
         {

            myProcess.StartInfo.FileName = path + "\\uged_ug.pdf";
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.Start();
         }
         catch (Win32Exception ex)
         {
            if (ex.NativeErrorCode == ERROR_FILE_NOT_FOUND)
            {
               MessageBox.Show(String.Format(ex.Message + "."));
            }

            else if (ex.NativeErrorCode == ERROR_ACCESS_DENIED)
            {
               // Note that if your word processor might generate exceptions
               // such as this, which are handled first.
               MessageBox.Show(String.Format(ex.Message +
                  ". You do not have permission to view this file."));
            }
         }
         catch (Exception ex1)
         {
            MessageBox.Show(String.Format(ex1.Message));
         }
      }

      private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
      {
         AboutBox1 f = new AboutBox1();

         f.ShowDialog();

      }

      private void newMenuItem_Click(object sender, EventArgs e)
      {
         string path = FolderMethods.GetUserPath();

         SaveFileDialog1.Title = "Create New Project";
         SaveFileDialog1.CreatePrompt = true;
         SaveFileDialog1.OverwritePrompt = true;

         // Set the file name to myText.txt, set the type filter
         // to text files, and set the initial directory to drive C.
         SaveFileDialog1.FileName = "New Uncle Ged Project.ugproj";
         SaveFileDialog1.DefaultExt = "ugp";
         SaveFileDialog1.Filter = "Uncle GED Project Files (*.ugproj)|*.ugproj";
         SaveFileDialog1.InitialDirectory = path;

         // Call ShowDialog and check for a return value of DialogResult.OK,
         // which indicates that the file was saved. 
         DialogResult result = SaveFileDialog1.ShowDialog();


         if (result == DialogResult.OK)
         {
            m_UGProj = new UGedProject();

            DisplaySettings();

            m_ProjectFileName = SaveFileDialog1.FileName;

            ConfigReader.SaveProject(m_ProjectFileName, m_UGProj);
            m_DidSave = true;
         }

      }

      private void txtFirstFamily_TextChanged(object sender, EventArgs e)
      {
        if(!Microsoft.VisualBasic.Information.IsNumeric(txtFirstFamily.Text))
        {
           txtFirstFamily.Text = "0";
        }
      }

      private void btnSetHtmlCompilerPath_Click(object sender, EventArgs e)
      {
         this.folderBrowserDialog1.SelectedPath = m_UGProj.HtmlHelpCompiler;

         if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
         {
            m_UGProj.HtmlHelpCompiler = this.folderBrowserDialog1.SelectedPath;
            this.txtHtmlHelpCompiler.Text = m_UGProj.HtmlHelpCompiler;
         }
      }

      private void cancelToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.Hide();
      }

      private void options_KeyDown(object sender, KeyEventArgs e)
      {
         if (e.KeyCode == Keys.Escape)
         {
            this.Hide();
         }
      }

   }
}